<template>
	<ve-dialog
		title="设置答案"
		width="1100px"
		:show.sync="isShowSetAnswerDialog"
		:on-close="cancel"
		class
	>
		<div class="answer-wrap">
			<ve-parse :article="replaceSpace" @click="handleCapture($event)" />
			<div class="option-wrap" :key="isUpdate">
				<div
					class="option-item"
					@click="setAnswer(item.answerOption)"
					v-for="(item, index) in questionAnswerList"
					:key="index"
				>
					{{ item.answerOption }}
				</div>
			</div>
		</div>
		<template #footer>
			<el-button class="save-btn" @click="cancel">取消</el-button>
			<el-button class="save-btn" @click="save" type="primary">确 定</el-button>
		</template>
	</ve-dialog>
</template>

<script>
export default {
    props: {
        questionContentTitle: {
            type: String,
            default: ''
        },
        questionAnswerList: {
            type: Array,
            default: () => {
                return [];
            }
        },
        questionAnswer: {
            type: String,
            default: ''
        },
        isShowSetAnswerDialog: {
            type: Boolean
        }
    },
    data () {
        return {
            inputWrapDom: [],
            curIndex: 0,
            answer: [],
            isUpdate: 0
        };
    },
    watch: {
        isShowSetAnswerDialog: {
            handler () {
                this.replaceSpace = this.replaceSpace();
                this.$nextTick(() => {
                    this.initInpWraoDom();
                    const newValArr = this.questionAnswer.split('※');

                    if(newValArr.length && newValArr.length===this.inputWrapDom.length){
                        //答案长度与输入框长度相同直接设置
                        this.answer = newValArr;
                    }else if(newValArr.length && newValArr.length!==this.inputWrapDom.length){
                        //答案长度与输入框长度不相同直接设置 证明选项或填空有增减，重新过滤答案
                        this.answer = new Array(this.inputWrapDom.length).fill('');
                        this.inputWrapDom.forEach((input,i)=>{
                            if(i+1>newValArr.length){
                                this.answer[i] = '';
                            } else {
                                this.answer[i] = newValArr[i];
                            }
                        });
                    } else {
                        //没有设置答案 --新增时
                        this.answer = new Array(this.inputWrapDom.length).fill('');
                    }
                    //防止答案和选项数据不匹配重新过滤
                    this.inputWrapDom.forEach((input,i)=>{
                        if(this.questionAnswerList.some(answer=>answer.answerOption===this.answer[i])){
                            //答案在选项中
                            this.answer[i] = newValArr[i];
                        } else {
                            //答案不在选项中
                            this.answer[i] = '';
                        }
                    });
                    //填充答案
                    this.inputWrapDom.forEach((ele, index) => {
                        console.log(this.answer[index]);
                        ele.innerText = this.answer[index];
                    });
                    this.curIndex  = this.inputWrapDom.findIndex(item => {
                        return !item.innerText;
                    });
                    this.setActive(this.curIndex);
                });
            },
            immediate: true,
            deep: true
        }
    },
    methods: {
        replaceSpace () {
            let i = 0;
            let tempStr = ('【选词填空】'+this.questionContentTitle).replace(/（\s*\)|\(\s*）|\(\s*\)|（\s*）/g, () => {
                return `<span data-index=${i} type="text" class="tkt_input"></span>
                `;
            });
            return tempStr;
        },
        // 初始化input
        initInpWraoDom () {
            this.inputWrapDom = Array.from(document.querySelectorAll('.tkt_input'));
            this.inputWrapDom.forEach((ele, index) => {
                // 绑定input事件
                ele.addEventListener('click', () => {
                    // 获取答案
                    this.setActive(index);
                    this.curIndex = index;
                });
            });
        },
        // 点击选项的处理逻辑
        setAnswer (item) {
            if (this.curIndex  === -1) return false;
            let inp = this.inputWrapDom[this.curIndex];
            inp.innerText = item;
            this.answer = this.inputWrapDom.map(item => item.innerText);
            // 自动聚焦下一个input框，并处理选项是否置灰
            this.$nextTick(() => {
                this.curIndex  = this.inputWrapDom.findIndex(item => {
                    return !item.innerText;
                });
                this.setActive(this.curIndex);
            });
        },
        setActive(index){
            this.inputWrapDom.forEach(inpDom => {
                inpDom.className = 'tkt_input';
            });
            if(index!==-1){
                this.inputWrapDom[index].className = 'tkt_input active';
            }
        },
        // 保存答案
        save () {
            if (this.answer.some(answer=>answer==='' || answer===null)) {
                this.$message({message: '请设置完整的题目答案', type: 'error'});
                this.curIndex  = this.inputWrapDom.findIndex(item => {
                    return !item.innerText;
                });
                this.setActive();
            } else {
                this.$emit('set-answer', this.answer);
            }
        },
        cancel(){
           this.$emit('cancel');
        }
    },
};
</script>

<style lang="less" scoped>
    /deep/.tkt_input {
        display:inline-block;
        background: rgba(0,0,0,0);
        border-top: none;
        border-left: none;
        border-right: none;
        outline: none;
        border-bottom: 1px solid #000;
        text-align: center;
        padding: 0 20px;
        color: #000;
        margin: 0 5px;
        &.active {
            color: #1890ff;
            border-bottom: 1px solid #1890ff;
        }
    }
    .option-wrap {
        display: flex;
        margin: 30px 0;
        flex-wrap: wrap;
        max-height: 500px;
        overflow-y: auto;
        .option-item {
            padding: 0 10px;
            background: #1890ff;
            line-height: 26px;
            margin-right: 10px;
            margin-bottom: 10px;
            color: #fff;
            font-size: 12px;
            border-radius: 1px;
            cursor: pointer;
        }
    }
</style>
